import time

import coin.exchange.base.kr_rest.public_client_base as pubcb
import coin.exchange.quoinex_v2.kr_rest.native_public_client as npubc
from coin.exchange.base.kr_rest.rest_client_base import RestUpdate
from coin.exchange.quoinex_v2.kr_rest.product import QuoinexProduct

from coin.proto.coin_market_query_pb2 import ProductTicker, ExchangeTicker


class QuoinexFeedParser(object):
  @staticmethod
  def parse_native_ticker(update_msg, product):
    return ProductTicker(last=float(update_msg['last_price_24h']),
                         ask=float(update_msg['market_ask']),
                         bid=float(update_msg['market_bid']),
                         volume_24hr=float(update_msg['volume_24h']),
                         native_symbol=product.native_symbol,
                         symbol=product.symbol)

  @classmethod
  def parse_exchange_ticker(cls, update_msg):
    product_ticker_list = []
    for msg in update_msg:
      native_symbol = msg['currency_pair_code']
      try:
        product = QuoinexProduct.FromStrNativeProduct(native_symbol)
        ticker = cls.parse_native_ticker(msg, product)
        product_ticker_list.append(ticker)
      except Exception as e:
        print(native_symbol, type(e), e)
        continue
    assert len(product_ticker_list) > 0
    return ExchangeTicker(exchange="Quoinex", each_ticker=product_ticker_list)


class QuoinexPublicClient(pubcb.PublicClientBase):
  ProductType = QuoinexProduct

  def __init__(self, timeout=1):
    self.npubc = npubc.QuoinexNativePublicClient(timeout=timeout)

  def query_ticker_impl(self, product):
    product_id = product.product_id
    update = self.npubc.get_ticker(product_id)
    update.msg = QuoinexFeedParser.parse_native_ticker(update.msg, product)
    return update

  def query_exchange_ticker_impl(self):
    req_time = time.time()
    ticker = self.npubc.queryAll().msg
    res_time = time.time()
    update = RestUpdate(req_time, res_time, ticker)
    update.msg = QuoinexFeedParser.parse_exchange_ticker(update.msg)
    return update

  def query_level_book_impl(self, product):
    raise NotImplementedError("Quoinex query level book Not Implemented")
